import { Button, Form, Input, App } from 'antd';
import { login } from '@/types';
import { loginRequst } from '@/api';
import storage from '@/utils/storage';
import styles from './index.module.less';
import store from '@/store';

export default function Login() {
  const updateToken = store(state => state.updateToken);
  const { message } = App.useApp();
  const onFinish = async (data: login.params) => {
    try {
      const token = (await loginRequst(data)) as string;
      storage.set<string>('token', token);
      updateToken(token);
      message.info('登陆成功');
      const params = new URLSearchParams(location.search);
      setTimeout(() => {
        location.href = params.get('callback') || '/';
      });
    } catch (err) {
      console.log(err);
    }
  };

  type FieldType = {
    userName?: string;
    userPwd?: string;
  };

  return (
    <div className={styles['login']}>
      <div className={styles['login-wrapper']}>
        <div className={styles['title']}>系统登陆</div>
        <Form
          name='basic'
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete='off'
        >
          <Form.Item<FieldType>
            name='userName'
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            name='userPwd'
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item>
            <Button
              type='primary'
              htmlType='submit'
              block
              style={{ height: 40 }}
            >
              登陆
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
